import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yinsh
 * Date: 2025-02-19
 * Time: 9:06
 */
public class MyHeap {
    private int[] array;
    private int usedSize;
    public MyHeap(int[] array) {
        this.array = array;
        this.usedSize = array.length;
    }
    public void initHeap() {
        if (usedSize == array.length) {
            array = Arrays.copyOf(array,array.length*2);
        }
        int parent = (usedSize - 2)/2;
        for (; parent >= 0; parent--) {
            shiftDown(parent);
        }
    }
    private void shiftDown(int parent) {
            int child = parent * 2 + 1;
            while (child < usedSize) {
                if (child + 1 < usedSize && array[child + 1] < array[child]) {
                    child++;
                }

                if (array[parent] < array[child]) {
                    break;
                } else {
                    swap(parent, child);
                    parent = child;
                    child = parent * 2 + 1;
                }
            }
    }

    private void swap(int x,int y) {
        if (array[x] > array[y]) {
            int tamp = array[x];
            array[x] = array[y];
            array[y] = tamp;
        }
    }
    public void heapSort() {
        int mark = usedSize - 1;
        while (mark > 0) {
                int tamp = array[0];
                array[0] = array[mark];
                array[mark] = tamp;
                mark--;
                usedSize--;
            int parent = (usedSize - 2)/2;
            for (; parent >= 0; parent--) {
                shiftDown(parent);
            }
            }
    }

}
